﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scryber.Testing.AllSystemTests
{
    public class CustomImageFactory : Scryber.IPDFImageDataFactory
    {
        private static Dictionary<string, Scryber.Drawing.PDFImageData> _cache = new Dictionary<string, Drawing.PDFImageData>();

        public Drawing.PDFImageData LoadImageData(string path)
        {
            string id = GetFileName(path);
            Scryber.Drawing.PDFImageData gen;
            if (!_cache.TryGetValue(id, out gen))
            {
                string text = System.Web.HttpUtility.UrlDecode(id);
                gen = GetCustomBitmap(text, id);
                _cache.Add(id, gen);
            }
            return gen;
        }

        private string GetFileName(string path)
        {
            int index = path.LastIndexOf('/');
            if (index < 0)
                index = path.LastIndexOf('\\');
            if (index > -1)
                path = path.Substring(index + 1);

            path = System.IO.Path.GetFileNameWithoutExtension(path);

            return path;
        }


        public static Scryber.Drawing.PDFImageData GetCustomBitmap(string text, string key)
        {
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(300, 200);
            bmp.SetResolution(100, 100);
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                g.FillRectangle(System.Drawing.Brushes.White, 0.0F, 0.0F, 300.0F, 300.0F);
                g.FillEllipse(new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(122, 255, 0, 0)), 25.0F, 0.0F, 150.0F, 150.0F);
                g.FillEllipse(new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(122, 0, 255, 0)), 125.0F, 0.0F, 150.0F, 150.0F);
                g.FillEllipse(new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(122, 0, 0, 255)), 75.0F, 50.0F, 150.0F, 150.0F);

                System.Drawing.RectangleF textarea = new System.Drawing.RectangleF(0.0F, 85.0F, 300.0F, 30.0F);
                g.FillRectangle(System.Drawing.Brushes.Black, textarea);

                //Draw the text string centered
                System.Drawing.Font font = new System.Drawing.Font("Arial", 12.0F, System.Drawing.FontStyle.Bold);
                System.Drawing.SizeF required = g.MeasureString(text, font, new System.Drawing.SizeF(300.0F, 100.0F));
                textarea.X = (300.0F - required.Width) / 2.0F;
                textarea.Y += (30.0F - required.Height) / 2.0F;

                g.DrawString(text, font, System.Drawing.Brushes.White, textarea);

            }
            return Scryber.Drawing.PDFImageData.LoadImageFromBitmap(key, bmp);
        }
    }
}
